#include "constants.h";

XfMissionChapterExecute={
	private ["_chapter_succeeded"];
	diag_log "";
	diag_log "=========================================================================";
	diag_log "                             CHAPTER 1                                   ";
	diag_log "=========================================================================";
	diag_log "";
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Starting Chapter","_last_random_reinforcement","_random_reinf_diff","_reinforcement_power"];
	DM_Mission_ArtilleryVariables = [];
	DM_Mission_Chapter_CanRun = True;
	DM_Mission_Chapter_Runs = True;
	DM_Mission_Chapter_Success = 0;
	call XfMissionChapterSetup;
	_chapter_succeeded = false;
	if (!DM_Mission_Mission_CanRun) exitWith {diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Mission canceled!"];};
	

	_player_detected = false;
	_tower_destroyed = false;
	_bunkers_taken = false;
	_bunkers_updated = false;
	_marked_bunkers = [];
	_detected_updated = false;
	_tower_updated = false;
	
	_enemy_initial_counts = ([DM_Chapter_Position,400,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
	_unique_id = 0;
	_reinforcements = 10;
	_detected_time = time;
	_reinforcement_trigger = _enemy_initial_counts / 4;
	
	// _flag_texture_owner = switch (d_enemy_side) do {
		// case "WEST": {"\ca\data\Flag_usa_co.paa"};
		// case "EAST": {"\ca\data\Flag_rus_co.paa"};
		// case "GUER": {"\ca\data\Flag_napa_co.paa"};
		// default {"\ca\data\Flag_napa_co.paa"};
	// };
	_flag_texture_owner = "\ca\data\Flag_napa_co.paa";
	switch (CurrentWorld) do {
		case "cla\clafghan\clafghan.wrp":
		{
			_flag_texture_owner = switch (d_enemy_side) do {
				case "WEST": {"\ca\data\Flag_usa_co.paa"};
				case "EAST": {"\ca\ca_e\data\flag_tka_co.paa"};
				case "GUER": {"\ca\ca_e\data\flag_tkm_co.paa"};
				default {"\ca\ca_e\data\flag_tkg_co.paa"};
			};
		};
		default
		{
			_flag_texture_owner = switch (d_enemy_side) do {
				case "WEST": {"\ca\data\Flag_usa_co.paa"};
				case "EAST": {"\ca\data\Flag_rus_co.paa"};
				case "GUER": {"\ca\data\Flag_napa_co.paa"};
				default {"\ca\data\Flag_napa_co.paa"};
			};
		};
	};

	
	// _flag_texture_taker = switch (d_own_side) do {
		// case "WEST": {"\ca\data\Flag_usa_co.paa"};
		// case "EAST": {"\ca\data\Flag_rus_co.paa"};
		// case "GUER": {"\ca\data\Flag_napa_co.paa"};
		// default {"FlagCarrierINS"};
	// };
	_flag_texture_taker = "\ca\data\Flag_napa_co.paa";
	switch (CurrentWorld) do {
		case "cla\clafghan\clafghan.wrp":
		{
			_flag_texture_taker = switch (d_own_side) do {
				case "WEST": {"\ca\data\Flag_usa_co.paa"};
				case "EAST": {"\ca\ca_e\data\flag_tka_co.paa"};
				case "GUER": {"\ca\ca_e\data\flag_tkm_co.paa"};
				default {"\ca\ca_e\data\flag_tkg_co.paa"};
			};
		};
		default
		{
			_flag_texture_taker = switch (d_own_side) do {
				case "WEST": {"\ca\data\Flag_usa_co.paa"};
				case "EAST": {"\ca\data\Flag_rus_co.paa"};
				case "GUER": {"\ca\data\Flag_napa_co.paa"};
				default {"\ca\data\Flag_napa_co.paa"};
			};
		};
	};
	
	diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Entering the loop",[_enemy_initial_counts,_reinforcement_trigger], Time];
	while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun} do {
		sleep 10;
		_enemy_counts = ([DM_Chapter_Position,400,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
		_tower_destroyed = ["jip_tower_is_destroyed",False] call XNetGetJIP;
		
		if (["jip_player_detected",false] call XNetGetJIP) then {_player_detected = true;};
		
		_bunkers_taken = true;
		if (typename DM_Target == "ARRAY") then {
			_bunkers_taken = true;
			if (count DM_Target > 0) then {
				{
					if (alive _x) then {
						_jip_var = _x getVariable "JIP_VAR";
						if (!([_jip_var,False] call XNetGetJIP)) then {
							_bunkers_taken = false;
							_x setFlagTexture _flag_texture_owner;
							if ((_x in _marked_bunkers)) then {
								(format["marker%1",_jip_var]) setMarkerColorLocal "ColorRed";
							};
						} else {
							_x setFlagTexture _flag_texture_taker;
							if (!(_x in _marked_bunkers)) then {
								[false,[format["marker%1",_jip_var],(getPos _x), "ICON", "ColorBlack", [0.7,0.7],"bunker",20,"mil_box","",0.6]] call XfMissionMarker;
								_marked_bunkers set [count _marked_bunkers, _x];
							} else {
								(format["marker%1",_jip_var]) setMarkerColorLocal "ColorBlack";
							};
						};
					};
				} foreach DM_Target;
			};
			if (!_bunkers_taken) then {
				_bunkers_updated = false;
			};
		};
		if (_tower_destroyed && !_tower_updated) then {
			_tower_updated = true;
			[getPos DM_VIP, d_side_enemy, 200] call XfMissionConvergeUnits;
		};
		
		If (_tower_destroyed && _bunkers_taken) then {
			"You took control of the town!" call XfMissionMessageToAll;
			_bunkers_updated = true;
			_chapter_succeeded = true;
			DM_Mission_Chapter_CanRun = false;
		};
		if (_bunkers_taken && !_bunkers_updated) then {
			_bunkers_updated = true;
			"You took the control of all bunkers!" call XfMissionMessageToAll;
		};

		if (d_mission_debug_messages) then { diag_log Format["(%1)[%2]: %3: %4: reinf:%5, tower:%6, bunkers:%7",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Status",_reinforcements,_tower_destroyed,_bunkers_taken]; };

		if (DM_Mission_Chapter_CanRun AND _player_detected and !_detected_updated) then {
			_detected_updated = true;
			"You are detected! Reinforcements will surely be called!" call XfMissionMessageToAll;
			_detected_time = time;
		};
		
		// diag_log Format["(%1)[%2]: %3: %4: en:%5  kill:%6  det:%7  flee:%8",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Loop",_enemy_counts,_dealer_killed,_player_detected,_dealer_fleeing];
		If (DM_Mission_Chapter_CanRun AND _player_detected AND (_reinforcements != 0) AND !_tower_destroyed) then {
			// If the player is detected and no reinforcement is on the way.. Then we send new troops in :)
			if ((_enemy_initial_counts - _enemy_counts) > _reinforcement_trigger) then {
				if (_unique_id == 0) then {
					// If the reinforcement function returns a value greater than 0, it means a reinforcement was created!
					_unique_id = [d_enemy_side,[DM_Chapter_Position,200],"RANDOM",DM_Mission_RandomReinforcement] call XfMissionCallReinforcement;
					if ((_unique_id) > 0) then {
						if (d_mission_debug_messages) then { diag_log Format["(%1)[%2]: %3: %4: reinf:%5, diff:%6, ini:%7",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Sending reinforcement",_reinforcements,_enemy_diff,_enemy_initial_counts]; };
						_reinforcements = _reinforcements - 1;
						// hint "Reinforcement";
					};
				};
			} else {
				_unique_id = 0;
			};
		};
	};
	
	if (DM_Mission_Mission_CanRun) then {
		if (_chapter_succeeded) then {
			call XfMissionChapterSuccess;
		} else {
			call XfMissionChapterFailure;
		};
	} else {
		diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Mission canceled!"];
	};
	
	_players_found = true;
	While {DM_Mission_Mission_CanRun && (([DM_Chapter_Position,400,d_enemy_side] call XfMissionGetZoneSideCount) select 0) > 3 && _players_found} do {
		sleep 5;
		_players_found = false;
		{
			if ([(getPos _x), DM_Chapter_Position, 600] call XfPointInCircle) exitWith { _players_found = true; };
		}foreach playableUnits;
	};
	// Just in case a reinforcement is already on the way.
	call XfMissionCancelReinforcement;
	call XfMissionChapterCleanUp;
	DM_Mission_Chapter_Runs = False;
};

XfMissionChapterSetup={
	private ["_random_town","_random_town_pos","_random_town_size","_troops_power","_troops_coeff","_grpSoldiers","_grpVehicle","_i"];
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Starting Initialization"];

	// We take towns AND villages
	_random_town = [true] call XfMissionGetRandomTown;
	while {(_random_town_pos distance FLAG_BASE) < 700} do {
		_random_town = [true] call XfMissionGetRandomTown;
	};
	if ((count _random_town) <= 0) exitWith {"Could not pick a random town" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	_random_town_pos = _random_town select XF_MAP_LOCATION_CENTER;
	
	DM_Chapter_Position = _random_town_pos;
	DM_Chapter_Location = _random_town;
	_random_town_size = _random_town select XF_MAP_LOCATION_SIZE;
	_random_town_name = _random_town select XF_MAP_LOCATION_DISPLAYNAME;
	diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Selected Town:",_random_town];
	
	if (_random_town_size < 150) then { _random_town_size = 150; };
	
	// This indicates where the mission takes place
	[_random_town_pos,_random_town_size,_random_town select 1] call XfMissionCurrentPosition;
	
	// We search a spot to place the teleporter which is around the town on a road (to avoid mountains and forests)
	_teleporter = [_random_town_pos] call XfMissionRandomStartTeleporter;
	// If no spot found, we get back an empty position.
	if (count (_teleporter select 0) > 0) then {
		[false,["chapter1_start_position",(_teleporter select 0), "ICON", "ColorBlue", [1,1],"",(_teleporter select 1),"hd_start","",1]] call XfMissionMarker;
	};
	
	// upsmon zone
	[true,["chapter1_random_town_zone", _random_town_pos, "ELLIPSE", "ColorRed", [_random_town_size * 1.5,_random_town_size * 1.5],"",0,"","BDiagonal",0.5]] call XfMissionMarker;
	// target zone
	[false,["chapter1_town_zone", _random_town_pos, "ELLIPSE", "ColorRed", [_random_town_size,_random_town_size],"",0,"","BDiagonal",0.5]] call XfMissionMarker;
	[false,["chapter1_town_cross",_random_town_pos, "ICON", "ColorRed", [1,1],"",20,"hd_destroy","",0.6]] call XfMissionMarker;
	
	_bunker_count = 2 + floor(random(2));
	_bunkers = [];

	_flag_type = "FlagCarrierINS";
	switch (CurrentWorld) do {
		case "cla\clafghan\clafghan.wrp":
		{
			_flag_type = switch (d_enemy_side) do {
				case "WEST": {"FlagCarrierUSA"};
				case "EAST": {"FlagCarrierTakistan_EP1"};
				case "GUER": {"FlagCarrierTKMilitia_EP1"};
				default {"FlagCarrierTakistan_EP1"};
			};
		};
		default
		{
			_flag_type = switch (d_enemy_side) do {
				case "WEST": {"FlagCarrierUSA"};
				case "EAST": {"FlagCarrierRU"};
				case "GUER": {"FlagCarrierGUE"};
				default {"FlagCarrierINS"};
			};
		};
	};
	
	DM_Target = [];
	for [{_i=0},{_i< _bunker_count},{_i = _i+1}] do {
		// We look for a spot to place a Warfare depot, to make sure a bunker fits
		_spot = [_random_town_pos,_random_town_size,"Land_fortified_nest_big"] call  XfMissionRanObjectivePos;
		if (count _spot > 0) then {
			_bunker = ["Land_fortified_nest_big",[_spot,random(360)],"REGISTER",[],"","CAN_COLLIDE"] call XfMissionCreateMissionObject;
			_bunker allowDamage false;
			_jip_var = format["jip_target_%1",_i];
			// Making a list only to give the right info in the task
			_bunkers set [count _bunkers, _bunker];
			
			_spot = _bunker modelToWorld [-0.17,0.2,-0.65];
			_takers = d_side_player;
			if (d_side_player == west) then { _takers = [d_side_player, resistance]; };
			_obj = [_flag_type,[_spot,0],"TAKEOVER",[7,"The bunker has been taken over by the allies!","Damn, they took the bunker back!",_jip_var,20,d_side_enemy,_takers],"","CAN_COLLIDE"] call XfMissionCreateMissionObject;
			_obj allowDamage false;
			_obj setVariable ["JIP_VAR",_jip_var];
			DM_Target set [count DM_Target, _obj];
			
			// Making cross references in case we need to link the objects in the chapter execution
			_bunker setVariable ["BunkerFlag",_obj];
			_obj setVariable ["BunkerFlag",_bunker];
		};
	};
	["TakeBunkers","Take the bunkers", Format["There are %1 bunkers in town that you need to capture!",count _bunkers],"",[],"Created"] call XfMissionTask;

	_spot = [_random_town_pos,((2 * _random_town_size) / 3),"Land_Vysilac_FM",_random_town_pos] call  XfMissionRanObjectivePos;
	if (count _spot == 0) then { _spot = _random_town_pos; };
	["jip_tower_is_destroyed",False] call XNetSetIP;
	DM_VIP = ["Land_Vysilac_FM",[_spot,random(360)],"DESTROY",["Congratulations, you destroyed the tower! The enemy cannot call reinforcement anymore!","jip_tower_is_destroyed",True,2,["PipeBomb"]]] call XfMissionCreateMissionObject;
	["DestroyTheTower","Destoy the Radio Tower", "Destroying the radio tower will prevent the enemy from calling reinforcement!","",[],"Created"] call XfMissionTask;

	_grpTowerGuards = [d_enemy_side,[_spot,15],[],0,false] call XfMissionCreateFootmenGroup;
	
	[d_enemy_side,[_random_town_pos,_random_town_size],true,0,0,1,0] call XfMissionPopulateLocation;
	// The trigger which will send reinforcement when the player is detected!
	["jip_player_detected",false] call XNetSetJIP;
	[_random_town_pos,_random_town_size * 2,d_own_side,d_enemy_side,"jip_player_detected"] call XfMissionSideDetected;
	// This will create snipers automatically if selected in the mission setup
	[d_enemy_side,[_random_town_pos,_random_town_size],DM_Mission_Snipers] call XfMissionCreateSnipersArea;
	// This will create air support automatically if selected in the mission setup
	[d_enemy_side,[_random_town_pos,_random_town_size],DM_Mission_AirSupport] call XfMissionCallAirSupport;
};

XfMissionChapterSuccess={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSuccess","Starting"];
	"Congratulations! Clean up any remaining enemies now." call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = 1;
};

XfMissionChapterFailure={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterFailure","Starting"];
	"You tried but failed... you'll do better next time." call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = -1;
};

// Self-explanatory
XfMissionChapterCleanUp={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterCleanUp","Starting"];
	// Giving an empty position places the teleporter back to the hangar, closing the hangar.
	[[],0] call XfMissionPlaceStartTeleporter;
	[] call XfMissionCleanMarkers;
	[] call XfMissionCleanTriggers;
	[] call XfMissionCleanTasks;
};

DM_Mission_Chapter_Compiled = true;